<?php
/**
 * Created by PhpStorm.
 * User: mars
 * Date: 2019/1/22
 * Time: 1:48 PM
 */

namespace api\models;


use common\libs\Constants;

class JobRecord extends \common\models\JobRecord
{

    public $order_id;

    public function fields()
    {
        return [
            'uid',
            'jid',
            'status',
            'order_id',
            'status_map' => function ($model) {
                return Constants::getJobRecordStatus();
            }

        ];
    }

    public function rules()
    {
        return [
            [['jid'], 'integer'],
            [['jid'], 'required'],
            ['jid', 'validateJid']
        ];
    }

    public function validateJid($attribute, $params)
    {
        if ( ! $this->hasErrors()) {
            if (Mission::findOne($this->jid) == null) {
                $this->addError($attribute, '任务不存在');
            } elseif (JobRecord::findOne(['uid' => \Yii::$app->getUser()->id, 'jid' => $this->jid])) {
                $this->addError($attribute, '已报名');
            }
        }
    }

    public function beforeSave($insert)
    {
        $this->order_id = null;
        $this->uid      = \Yii::$app->getUser()->id;
        $this->status   = self::STATUS_SIGN_UP;
        if (Job::findOne($this->jid)->type == Job::MISSION_TYPE) {
            $good           = Good::findByCode("take_mission");
            $this->order_id = Order::generateOrderByGoodId($good->id, Order::TYPE_TAKE_MISSION, 1, uniqid(),
                $this->jid)->order_id;
            $this->status   = self::STATUS_NOT_PAY;
        }

        return parent::beforeSave($insert);
    }

}